import React, { memo, useCallback, useEffect, useRef, useState } from "react";
import PlayerWarrper from "./style";
import {
  UpOutlined,
  HeartOutlined,
  PauseCircleOutlined,
  CloudDownloadOutlined,
  MessageOutlined,
  YoutubeOutlined,
  SoundOutlined,
  MenuOutlined,
  RadiusBottomleftOutlined,
  UndoOutlined,
  RetweetOutlined,
} from "@ant-design/icons";
import songTimeFormat from "@/util/SongTimeFormat";
import {
  DownOutlined,
  PlayCircleOutlined,
  StepBackwardOutlined,
  StepForwardOutlined,
  MenuUnfoldOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons";
import { Drawer, Popconfirm, Slider } from "antd";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import {
  changeIndex,
  changeIsPlay,
  changePlayModel,
  changeTimer,
  getLyricInfo,
  getPlayerInfo,
} from "@/store/modules/playerSlice";
import classNames from "classnames";
import { useNavigate } from "react-router-dom";
import LyricModel from "./player-lyric/index";
const index = memo(() => {
  const dispatch = useDispatch();
  const audio = useRef();
  const [position, changPosition] = useState(100);
  const [positionRight, changePositionRight] = useState(100);
  const [nowTime, changeTime] = useState(0);
  const navigate = useNavigate();
  // ,singerName,picName,picUrl
  const { picUrl, id, isPlay, playList, player, index, playModel } =
    useSelector((state) => {
      return {
        id: state?.player?.player?.id,
        songName: state?.player?.player?.name || "",
        singerName: state?.player?.player?.ar,
        picUrl: state?.player?.player?.al?.picUrl,
        isPlay: state.player.isPlay,
        player: state.player.player,
        playList: state.player.playerList,
        index: state.player.playerIndex,
        playModel: state.player.playModel,
      };
    }, shallowEqual);
  const playerSong = useCallback(() => {
    if (
      audio.current.src !==
      `https://music.163.com/song/media/outer/url?id=${playList[index]?.id}.mp3`
    ) {
      audio.current.src = `https://music.163.com/song/media/outer/url?id=${playList[index]?.id}.mp3`;
    }
    audio.current.play();
    dispatch(changeIsPlay(true));
    dispatch(getLyricInfo(playList[index].id));
  }, [playList, index]);
  const pauseSong = useCallback(() => {
    audio.current.pause();
    dispatch(changeIsPlay(false));
  }, [dispatch]);
  useEffect(() => {
    if (isPlay) {
      if (playList.length >= 1) {
        changeTime(0);
        playerSong(id);
      }
    } else {
      if (playList.length >= 1) {
        pauseSong();
      }
    }
  }, [isPlay, playerSong, id]);
  const [nprog, changeNprog] = useState(0);
  const [isUpdateNprog, changeUPNP] = useState(false);
  const timeUpdate = (e) => {
    if (
      Math.floor(e.target.currentTime) >= Math.floor(playList[index].dt / 1000)
    ) {
      changeSongIndex();
    }
    changeTime(e.target.currentTime);
    dispatch(changeTimer(e.target.currentTime));
    if (!isUpdateNprog)
      changeNprog((nowTime / (playList[index].dt / 1000)) * 100);
  };
  const changeSlider = useCallback((value) => {
    changeUPNP(true);
    changeNprog(value);
  }, []);
  const changeAfterSlider = useCallback(
    (value) => {
      audio.current.currentTime = Math.floor(
        ((value / 100) * playList[index].dt) / 1000
      );
      // 如果太快让进度条被audio的时间调控，将会出现进度条闪烁，故用延时器延迟
      setTimeout(() => {
        changeUPNP(false);
      }, 500);
      changeNprog(value);
    },
    [playList]
  );
  const [open, setOpen] = useState(false);
  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };
  const palySong = (id) => {
    dispatch(getPlayerInfo(id));
    dispatch(changeIsPlay(true));
  };
  // 点击去歌曲的MV
  const goToMV = (mv) => {
    navigate("/playMV/" + mv);
    dispatch(changeIsPlay(false));
  };
  // 更改页面title为歌曲名字
  useEffect(() => {
    document.title = `▶ ${playList[index]?.name}`;
  }, [palySong]);
  // 上一首/下一首歌曲切换
  const changeSongIndex = (flag = true) => {
    // 为true的时候，切换下一首
    if (flag) {
      if (index >= playList.length - 1) {
        if (playList[0]?.id) {
          dispatch(getLyricInfo(playList[index].id));
        }
        dispatch(changeIndex(0));
      } else {
        dispatch(changeIndex(index + 1));
        if (playList[index + 1]?.id) {
          dispatch(getLyricInfo(playList[index + 1].id));
        }
      }
      playerSong();
      
    } else {
      // 为false的时候，切换上一首
      // 当下标为
      let nindex = index;
      if (index <= 0) {
        nindex = playList.length - 1;
      } else if (index >= playList.length - 1) {
        nindex = 0;
      } else {
        nindex--;
      }
      dispatch(getLyricInfo(playList[nindex].id));
      dispatch(changeIndex(nindex));
    }
  };
  const [showModel, changeModel] = useState(false);
  const changeSongModel = () => {
    changeModel(!showModel);
  };
  const changeModelCode = (code) => {
    dispatch(changePlayModel(code));
    changeModel(false);
  };

  const onChangeVolume = (e) => {
    changvolum(e);
    audio.current.volume = e / 100;
  };
  // 是否展示声音组件
  const [showVolum, changeVolum] = useState(false);
  // 声音组件的音量大小
  const [volum, changvolum] = useState(100);
  // 方法：点击声音图标触发，当显示声音组件的时候，同步audio的声音大小
  const changeControlVolum = () => {
    changeVolum(!showVolum);
    if (showVolum) {
      changvolum(audio.current.volume * 100);
    }
  };
  // 声音组件DOM
  const sound = useRef();
  // 播放模式组件DOM
  const modelDom = useRef();
  const onAfterChangeVolume = (e) => console.log(e);
  const modelAndSoundClick = useCallback((e) => {
    e.stopPropagation();
    if (modelDom?.current && !modelDom?.current?.contains(e.target)) {
      changeModel(false);
    }
    if (!sound?.current?.contains(e.target)) {
      changeVolum(false);
    }
  }, []);
  document.documentElement.addEventListener("click", modelAndSoundClick);
  useEffect(() => {
    return () => {
      document.documentElement.removeEventListener("click", modelAndSoundClick);
    };
  }, []);
  const listchangeSong = ({ i, id }) => {
    dispatch(changeIndex(i));
    dispatch(getLyricInfo(id));
  };
  return (
    <div>
      <audio ref={audio} onTimeUpdate={timeUpdate}></audio>
      <div className="slider-main">
        <Slider
          className="slider"
          defaultValue={0}
          value={nprog}
          onChange={changeSlider}
          onAfterChange={changeAfterSlider}
        />
      </div>
      <PlayerWarrper
        position={position}
        positionRight={positionRight}
        picUrl={picUrl}
      >
        <div className="left" onClick={(e) => changPosition(0)}>
          <div className="songInfo">
            <img className="img" src={playList[index]?.al?.picUrl} alt="" />
            <div className="info">
              <div className="info-text">
                {playList[index]?.name} - {playList[index]?.ar[0]?.name}
              </div>
              <div className="info-icon">
                <HeartOutlined className="ic" />
                <CloudDownloadOutlined className="ic" />
                <MessageOutlined className="ic" />
              </div>
            </div>
          </div>
          <div className="left_cover">
            <UpOutlined />
          </div>
        </div>
        <div className="center">
          {/* 播放模式按钮模块 */}
          <div className="play-model" ref={modelDom}>
            {showModel && (
              <ul className="model">
                <li onClick={(e) => changeModelCode(0)}>
                  <RetweetOutlined className="mi" />
                  列表循环
                </li>
                <li onClick={(e) => changeModelCode(1)}>
                  <UndoOutlined className="mi" />
                  单曲循环
                </li>
                <li onClick={(e) => changeModelCode(2)}>
                  <RadiusBottomleftOutlined className="mi" />
                  随机播放
                </li>
              </ul>
            )}
            {playModel === 0 && (
              <RetweetOutlined
                onClick={(e) => changeSongModel()}
                className="icon"
              />
            )}
            {playModel === 1 && (
              <UndoOutlined
                onClick={(e) => changeSongModel()}
                className="icon"
              />
            )}
            {playModel === 2 && (
              <RadiusBottomleftOutlined
                onClick={(e) => changeSongModel()}
                className="icon"
              />
            )}
          </div>
          {/* 上一首按钮 */}
          {playList.length >= 2 ? (
            <StepBackwardOutlined
              className="lp"
              onClick={(e) => changeSongIndex(false)}
            />
          ) : (
            <StepBackwardOutlined className="lp2" />
          )}
          {/* 播放按钮 */}
          {!isPlay ? (
            <PlayCircleOutlined
              className="play"
              onClick={(e) => playerSong(id)}
            />
          ) : (
            <PauseCircleOutlined
              className="play"
              onClick={(e) => pauseSong()}
            />
          )}
          {/* 下一首按钮 */}
          {playList.length >= 2 ? (
            <StepForwardOutlined
              className="lr"
              onClick={(e) => changeSongIndex(true)}
            />
          ) : (
            <StepForwardOutlined className="lr2" />
          )}
          <div className="sound" ref={sound}>
            <a title="点击打开音量或者关闭">
              <SoundOutlined className="lt" onClick={changeControlVolum} />
            </a>
            {showVolum && (
              <div className="control-sound">
                <Slider
                  vertical
                  value={volum}
                  defaultValue={volum}
                  onAfterChange={onAfterChangeVolume}
                  onChange={onChangeVolume}
                />
                {volum}%
              </div>
            )}
          </div>
        </div>
        <div className="right">
          {songTimeFormat(nowTime * 1000)}/{songTimeFormat(playList[index]?.dt)}{" "}
          &nbsp;
          <div className="tabs" onClick={(e) => showDrawer()}>
            <MenuUnfoldOutlined />
            &nbsp;{playList?.length}
          </div>
        </div>
        <LyricModel position={position} changPosition={changPosition} />

        <Drawer
          title="播放队列"
          closable={false}
          placement="right"
          onClose={onClose}
          open={open}
          footer={
            <div
              style={{
                textAlign: "right",
                height: 50,
                display: "flex",
                alignItems: "center",
                justifyContent: "flex-end",
              }}
            >
              <MenuUnfoldOutlined />
              &nbsp;收起&nbsp;&nbsp;
            </div>
          }
        >
          {playList.map((n, i) => {
            return (
              <div
                key={i}
                className={classNames("songlist", {
                  songActive: n.id == playList[index].id,
                })}
                style={{ backgroundColr: "red" }}
              >
                <img src={n?.al?.picUrl} alt="" />
                <div className="common-info">
                  <div className="top">
                    {n?.name}
                    {n?.mv != 0 ? (
                      <YoutubeOutlined
                        className="ic"
                        onClick={(e) => goToMV(n.mv)}
                      />
                    ) : (
                      ""
                    )}
                    {n?.fee == 8 ? (
                      <span className="hightSongIcon">Hi-Res</span>
                    ) : (
                      ""
                    )}
                  </div>
                  <div className="bottom">
                    <div className="bot-left">{n?.ar[0]?.name}</div>
                    {/* <div className="bot-right">{n?.al?.name}</div> */}
                  </div>
                </div>
                <div
                  className="play-queue-btns"
                  style={{ display: n.id == playList[index].id ? "flex" : "" }}
                >
                  {n.id == playList[index]?.id ? (
                    <PauseCircleOutlined className="ic" />
                  ) : (
                    <PlayCircleOutlined
                      className="ic"
                      onClick={(e) => listchangeSong({ i, id: n.id })}
                    />
                  )}
                  <HeartOutlined className="ic" />
                  <MessageOutlined className="ic" />
                </div>
              </div>
            );
          })}
        </Drawer>
      </PlayerWarrper>
    </div>
  );
});

export default index;
